package cn.jimmie.lib.qlog.demo;

import android.content.Context;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Func :
 *
 * <p> Create Time:  2019-12-18 10:02 </p>
 * <p> @author Jimmie.Qian  </p>
 */
public class MmapTask {
    private static final int BUFF_SIZE = 16 * 1024;
    private static final int FLUSH_SIZE = 8 * 1024;
    private byte[] buff = new byte[BUFF_SIZE];
    private int position = 0;

    private MappedByteBuffer mbb;

    public void init(Context ctx) {
        try {
            String path = ctx.getExternalFilesDir("") + File.separator + "qlog_mmap_cache";
            FileChannel fileChannel = new RandomAccessFile(new File(path), "rw").getChannel();
            mbb = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, BUFF_SIZE);
        } catch (Throwable ignored) {
        }
    }

    public void write(String message) {
        if (mbb == null) return;
        mbb.put(message.getBytes());
    }

    public String read() {
        if (mbb == null) return "";
        mbb.position(0);
        mbb.get(buff);
        mbb.position(0);
        return new String(buff).trim();
    }
}
